Page({
    data: {
      parentId: "",
      username: "",
      avatar: "/assets/images/avatar.png",
      realName: "",
      sex: 1,
      age: "",
      tel: "",
      idCard: "",
      emergencyContact: "",
      emergencyTel: "",
      address: ""
    },

    onLoad() {
      this.fetchUserInfo();
    },

    fetchUserInfo() {
        const tel = wx.getStorageSync('tel');
        console.log("📌 获取的 tel:", tel); // ✅ 调试点
      
        if (!tel) {
          wx.showToast({ title: '请先登录', icon: 'none' });
          return;
        }
      
        wx.request({
          url: `http://localhost:8081/parent/info/${tel}`,
          method: "GET",
          header: {
            'Authorization': `Bearer ${wx.getStorageSync('token')}`,
            'content-type': 'application/json'
          },
          success: (res) => {
            console.log("📌 获取用户信息:", res.data); // ✅ 调试点
            if (res.data) {
              this.setData({
                parentId: res.data.parentId || "",
                username: res.data.username || "",
                avatar: res.data.avatar || "/assets/images/avatar.png",
                realName: res.data.realName || "",
                sex: res.data.sex !== undefined ? res.data.sex : 1, 
                age: res.data.age !== undefined ? res.data.age : "",
                tel: res.data.tel || tel,  // ✅ 读取 `wx.getStorageSync('tel')`
                idCard: res.data.idCard || "",
                emergencyContact: res.data.emergencyContact || "",
                emergencyTel: res.data.emergencyTel || "",
                address: res.data.address || ""
              });
            }
          },
          fail: (err) => {
            console.error("❌ 获取用户信息失败:", err);
            wx.showToast({ title: '获取信息失败', icon: 'none' });
          }
        });
    },

    onInputChange(e) {
      const { field } = e.currentTarget.dataset;
      this.setData({ [field]: e.detail.value });
      console.log(`📌 更新 ${field}:`, e.detail.value); // ✅ 调试点
    },

    // ✅ 解决“修改头像”问题，新增 uploadAvatar 方法
    uploadAvatar() {
        wx.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            console.log("📌 选择的头像:", res.tempFilePaths[0]); // ✅ 调试点
            this.setData({ avatar: res.tempFilePaths[0] });
            wx.setStorageSync('avatar', res.tempFilePaths[0]); // ✅ 同步到本地存储
          },
          fail: (err) => {
            console.error("❌ 选择头像失败:", err);
          }
        });
      },
      

    updateProfile() {
      console.log("📌 提交修改信息:", this.data); // ✅ 调试点

      if (!this.data.parentId) {
        wx.showToast({ title: '用户ID不能为空', icon: 'none' });
        return;
      }

      wx.request({
        url: 'http://localhost:8081/parent/update',
        method: 'PUT',
        data: {
          parentId: this.data.parentId,
          username: this.data.username,
          avatar: this.data.avatar,
          realName: this.data.realName,
          sex: Number(this.data.sex),  // ✅ 确保 sex 是 Number
          age: Number(this.data.age),  // ✅ 确保 age 是 Number
          tel: this.data.tel,
          idCard: this.data.idCard,
          emergencyContact: this.data.emergencyContact,
          emergencyTel: this.data.emergencyTel,
          address: this.data.address
        },
        header: {
          'content-type': 'application/json',
          'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        success: (res) => {
          console.log("✅ 服务器返回:", res); // ✅ 调试点
          if (res.statusCode === 200) {
            wx.showToast({ title: '更新成功', icon: 'success' });
            wx.navigateBack();
          } else {
            console.error("❌ 更新失败:", res.data);
            wx.showToast({ title: res.data || '更新失败', icon: 'none' });
          }
        },
        fail: (err) => {
          console.error("❌ 网络请求失败:", err);
          wx.showToast({ title: '更新失败，请重试', icon: 'none' });
        }
      });
    }
});
